require('es6-promise').polyfill();

import axios from 'axios'

import ApiMsgAction from './ApiMsgAction'

export function deleteUserBind(id) {
  return {
    type: 'DELETE_USER_BIND',
    id
  };
}

function loadUsers(data) {
  return {
    type: 'LOAD_USERS',
    data
  }
}

function updateUser(data) {
  return {
    type: 'UPDATE_EXPIRE_TIME',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_USERS_SETTING',
    error
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

export function updateUsersAsync(data) {
  return function(dispatch) {
    return axios.post('/api/user_settings/update', data).then(
      resp => dispatch(loadUsersAsync({
        offset: data.offset,
        limit: data.limit,
        name: data.search
      })),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function deleteUserBindAsync(data) {
  return function(dispatch) {
    return axios.post('/api/user_settings/delete_bind', data).then(
      resp => dispatch(loadUsersAsync({
        offset: data.offset,
        limit: data.limit,
        name: data.search
      })),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function createUserBindAsync(data) {
  return function(dispatch) {
    return axios.post('/api/user_settings/create', data).then(
      resp => dispatch(loadUsersAsync({})),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function loadUsersAsync(filter) {
  return function(dispatch) {
    return axios.post('/api/user_settings', filter).then(
      resp => dispatch(loadUsers(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}
